<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>03_回到顶部</title>
  <style>
    #to_top {
      width: 30px;
      height: 40px;
      font: 14px/20px arial;
      text-align: center;
      background: #06c;
      position: fixed;
      cursor: pointer;
      color: #fff;
      left: 1250px;
      top: 500px;
    }
  </style>
</head>
<body style="height: 2000px;">

<div id="to_top">返回顶部</div>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script>
  //瞬间回到顶部
  var intervalId
  $('#to_top').click(function () {
    clearInterval(intervalId)
    // $('html,body').scrollTop(0)
    var $page = $('html,body')
    //得到距离页面顶部的距离
    var distance = $('html').scrollTop() + $('body').scrollTop()
    //设置滑动总时间
    var time = 500
    //设置滑动的间隔时间
    var itemTime = 50
    //计算每段距离
    var itmeDis = distance / (time / itemTime)
    // 设置定时器，分段滑动
    intervalId = setInterval(function () {
      distance -= itmeDis
      if (distance < 0){
        distance = 0
        clearInterval(intervalId)
      }
      $page.scrollTop(distance)
    },itemTime)
  })
</script>
</body>

</html>